// 封装购物车模块

import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { useUserStore } from "./userStore";
import { insertCartAPI, findNewCartListAPI, delCartAPI } from '@/apis/cart'
import { ElMessage } from "element-plus";

export const useCartStore = defineStore('cart', () => {
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.userInfo != null)
    // 定义 state - cartList
    const cartList = ref([])

    // 获取最新购物车列表 action
    const updateNewList = async () => {
        const res = await findNewCartListAPI()
        // 覆盖本地购物车列表 TODO 是不是合并更好？？
        cartList.value = res.data
    }

    // 将购物车列表中相同卖家的商品合并为一个卖家对象的数组
    const sellers = computed(() => {
        const map = new Map();
        cartList.value.forEach(item => {
            if (!map.has(item.goodsCreateByName)) {
                map.set(item.goodsCreateByName, []);
            }
            map.get(item.goodsCreateByName).push(item);
        });

        // 更新卖家的 checked 属性
        Array.from(map).forEach(([name, items]) => {
            const allSelected = items.every(item => item.selected);
            items.forEach(item => item.checked = allSelected);
        });

        return Array.from(map).map(([name, items]) => ({ name, items, checked: items.every(item => item.checked) }));
    });

    // 定义 action - addCart
    const addCart = async (goods) => {
        const { goodsId, skuId, count } = goods
        console.log("添加购物车" + goodsId)
        console.log("isLogin" + isLogin.value)
        if (isLogin.value) {
            console.log(goodsId)
            console.log(count)
            // 登录之后的加入购物车逻辑
            await insertCartAPI({ goodsId, count })
            await updateNewList()
        } else {
            // 添加购物车逻辑
            // 已经添加过 count+1
            // 没有添加过 - 直接 push
            // 思路：通过传过来的 skuId 去匹配
            const item = cartList.value.find((item) => goods.id === item.goodsId)
            if (item) {
                // 找到了
                item.count++
            } else {
                // 没找到
                cartList.value.push(goods)
            }
            console.log(cartList)
            console.log(goods)
        }
        ElMessage.success("添加【" + goods.name + "】" + "购物车成功")

    }

    // 删除商品
    const delCart = async (id) => {
        if (isLogin.value) {
            // 调用接口实现接口购物车中的删除功能
            await delCartAPI([id])
            await updateNewList()
        } else {
            // 思路：找到删除项的下标值 - splice  使用数组的过滤方法
            const idx = cartList.value.findIndex((item) => id === item.id)
            cartList.value.splice(idx, 1)
        }

    }

    // 清除购物车
    const clearCart = () => {
        cartList.value = []
    }

    // 单选功能
    const singleCheck = (id, selected) => {
        // 通过 skuId 找到需要修改的 item
        const item = cartList.value.find((item) => item.id === id)
        item.selected = selected
    }

    // 全选功能
    const allCheck = (seller,selected) => {
        // 把 cartList 的 selected 都设置位 true
        cartList.value.filter(item => item.goodsCreateByName === seller.name).forEach(item => item.selected = selected)
    }

    // 计算属性
    // 1. 总数：所有项的 count 之和
    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
    // 2. 总价：count * price
    const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))

    // 3. 已选择数量
    const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
    // 4. 已选择商品价格合计
    const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0))
    // 是否全选
    const isAll = computed(() => cartList.value.every((item) => item.selected))

    return {
        cartList,
        allCount,
        allPrice,
        selectedCount,
        selectedPrice,
        isAll,
        sellers,
        updateNewList,
        addCart,
        delCart,
        clearCart,
        singleCheck,
        allCheck
    }
}, {
    persist: true
})
